package com.huifaapp.mall.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.google.gson.Gson;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.Seearch_showAdapter;
import com.huifaapp.mall.adapter.TmallchoicenessAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.bean.JDlianjie;
import com.huifaapp.mall.bean.SearchBean;
import com.huifaapp.mall.bean.ShareImageBean;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.uitils.ShareUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.kepler.jd.Listener.LoginListener;
import com.kepler.jd.login.KeplerApiManager;
import com.kepler.jd.sdk.exception.KeplerBufferOverflowException;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huifaapp.mall.afinal.Constants.savePath;

/**
 * Created by duanyu on 2018/2/1.
 */

public class Search_showActivity extends AppCompatActivity {

    private XRecyclerView activity_search_show_list;
    private String keyword;
    private  String  LISTURL= ApiManager.BASE_NIUPAI_URL+"goods/list";
    private  int curr;
    private List<SearchBean.DataBean.ListBean> searchBeanlist;
    private Seearch_showAdapter seearch_showAdapter;
    private String categoryId;
    private String spuPlatform;
    private int location;
    private String datayouhui;
//    private  String SYNCJDSPREADURL=ApiManager.BASE_NIUPAI_URL+Contig.typex+"/getUrl";//京东普通二合一链接
//    private  String GETCONURLURL=ApiManager.BASE_NIUPAI_URL+Contig.typex+"/getConUrl";//京东获取优惠劵二合一链接
    private String datalisnajie;
    private JDlianjie jDlianjiebean;
    private LinearLayout mActivity;
    private TextView mActivityTv;
    private TextView mProductTv;
    private LinearLayout mProduct;
    private TextView mSortTv;
    private LinearLayout mSort;
    private ListView mSupplierListLv;
    private ArrayList <Map<String, String> >mMenuData3;
    private ArrayList mMenuData2;
    private  ArrayList <Map<String, String> > mMenuData1;
    private PopupWindow mPopupMenu;
    private ListView mPopListView;
    private SimpleAdapter mMenuAdapter1;
    private SimpleAdapter mMenuAdapter3;
    private int menuIndex = 0;
    private ImageView supplier_list_xaiohui;
    private LinearLayout zhanweill;
    private TextView tv_searsss;
    private TextView tv_title_sear;
    private String titlename;
    ArrayList<String> idlist = new ArrayList<>();
    public static Map<Integer, Boolean> hmap;
    private ImageView dialog_search_share;
    private static final int SHARET_WXHY = 517;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_show);
        hmap = new HashMap<>();
        tv_title_sear= (TextView) findViewById(R.id.tv_title_sear);
        dialog_search_share= (ImageView) findViewById(R.id.dialog_search_share);
        Intent Intent=getIntent();
            keyword = Intent.getStringExtra("keyword");
            titlename = Intent.getStringExtra("titlename");
            Contig.hos.add(keyword);
            tv_title_sear.setText(titlename);

            Log.e("keyword",keyword);
//            Log.e("categoryId",categoryId);
            Log.e("搜索接口",LISTURL+"?"+"&type="+"yh"+"&categoryId="+keyword+"&keyword="+keyword);


        initView();
        //ButterKnife的初始化
       ButterKnife.bind(this);
        //初始化Popuwindow显示的数据
        initDatapopw();
        //初始化popuwindow控件
        initPopMenu();


    }


    private void initDatapopw() {
        mMenuData1 = new ArrayList<>();
        //存放String的字符串数组
        String[] menuStr1 = new String[]{"综合排序", "价格由高到低", "价格由低到高"
        };
        //创建一个小盒子,放编号和值
        Map<String, String> map1;
        for (int i = 0, len = menuStr1.length; i < len; ++i) {
            map1 = new HashMap<String, String>();
            map1.put("name", menuStr1[i]);
            mMenuData1.add(map1);
        }
        //创建一个存放popupwindow加载数据的大盒子2,Map集合(键,值)
        mMenuData2 = new ArrayList<>();
        String[] menuStr2 = new String[]{};
        Map<String, String> map2;
        for (int i = 0, len = menuStr2.length; i < len; ++i) {
            map2 = new HashMap<String, String>();
            map2.put("name", menuStr2[i]);
            mMenuData2.add(map2);
        }
        //创建一个存放popupwindow加载数据的大盒子3,Map集合(键,值)
        mMenuData3 = new ArrayList<>();
        String[] menuStr3 = new String[]{"红包由高到低", "红包由低到高"};
        Map<String, String> map3;
        for (int i = 0, len = menuStr3.length; i < len; ++i) {
            map3 = new HashMap<String, String>();
            map3.put("name", menuStr3[i]);
            mMenuData3.add(map3);
        }
    }

    private void requestEmit(String orderType) {
        Log.e("搜索排序接口",LISTURL+"?orderType="+orderType+"&keyword="+keyword);
        OkHttpUtils.post().addParams("keyword",keyword)
                .addParams("orderType",orderType)
                .url(LISTURL).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Log.e("categoryCode",response);
                activity_search_show_list.refreshComplete();

                initData(response);
            }
        });
    }

    private void initData(String response) {
        Log.e("搜索页数据",response);
        Gson gson = new Gson();
        SearchBean babyBean = gson.fromJson(response,SearchBean.class);
        if (babyBean.getCode().equals("10000")){
            if (babyBean != null && babyBean.getData() != null && babyBean.getData().getList() != null) {
                if (curr == 0) {
                    searchBeanlist.clear();
                }

                searchBeanlist.addAll(babyBean.getData().getList());
                seearch_showAdapter.notifyDataSetChanged();
            }
        }

    }
    private void initPopMenu() {
        //把包裹的ListVIew的布局XML文件转换为VIew对象
        View popView = LayoutInflater.from(this).inflate(R.layout.popwin_supplier_list, null);
        //创建popuwindow对象,参数1popuwindow要显示的布局,参数2,3:定义popuwindow所占用的宽高
        mPopupMenu = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        //设置popuwindow外部可以点击              true:可以，      false:不可以
        mPopupMenu.setOutsideTouchable(true);
        //是popuwindow里填充的listView拥有焦点
        mPopupMenu.setFocusable(true);
        //如果想要让popuwindow具有一些操作,比如动画效果之类的,必须给popuwindow设置背景
        mPopupMenu.setBackgroundDrawable(new ColorDrawable());
        //设置popuwindow的动画效果
//        mPopupMenu.setAnimationStyle(R.style.popwin_anim_style);
        //设置popuwindow结束时的监听事件
        mPopupMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //设置TextView的颜色,把所有LinearLayout的文本颜色该为灰色
                mProductTv.setTextColor(Color.parseColor("#5a5959"));
                mSortTv.setTextColor(Color.parseColor("#5a5959"));
                mActivityTv.setTextColor(Color.parseColor("#5a5959"));
            }
        });
        //点击popuwindow以外的区域,使popuwindow消失(实际就是让ListView下面的LinerLayout,设置点击事件)
        LinearLayout list_bottom= (LinearLayout) popView.findViewById(R.id.popwin_supplier_list_bottom);
        list_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //当LinerLayout被点击时,这popuwindow消失
                mPopupMenu.dismiss();
            }
        });

        //获取listVIew对象
        mPopListView = (ListView) popView.findViewById(R.id.popwin_supplier_list_lv);
        //点击popuwindow以外区域时,使popuwindow消失.在这里得到了ListView下面的LinearLayout,设置监听事件
/*SimpleAdapter 简单数据适配器:正好有一组数据,是Map集合放到ArrayList集合,就可以使用这个适配器了,不是太常用,设置数据太麻烦.
context:上下文    data:设置所有条目的数据,一个ArrayList大集合(包含所有条目信息),里面又有一个map集合(通过map来设置一个条目的数据)
resource:引用布局资源(可以引用复杂的布局.xml文件,区别于ArrayAdapter)
from:String数组,装map条目内容的键            to:int数组,装控件id  二者具有映射关系,代表对应的内容放到对应的位置*//*
ArrayList<Map<String,Object>> data=new ArrayList<Map<String,Object>>();
        //注意:一个map,代表一条item的数据.
        Map<String,Object> map=new HashMap<String, Object>();
        ListView对象.setAdapter(new SimpleAdapter(context, data, resource, from, to));*/
        //创建SimpleAdapter,一个listView安卓原生封装的适配器
        mMenuAdapter1 = new SimpleAdapter(this, mMenuData1,
                R.layout.item_listview_popwin, new String[]{"name"}, new int[]{R.id.listview_popwind_tv});
        mSort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestEmit("totalSalesDesc");
            }
        });

//        mMenuAdapter2 = new SimpleAdapter(this, mMenuData2,
//                R.layout.item_listview_popwin, new String[]{"name"}, new int[]{R.id.listview_popwind_tv});

        mMenuAdapter3 = new SimpleAdapter(this, mMenuData3,
                R.layout.item_listview_popwin, new String[]{"name"}, new int[]{R.id.listview_popwind_tv});

        //设置Popuwindow里的listView点击事件,当点击listVIew里的一个item时,把这个item数据显示到最上方
        mPopListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long ld) {
                //首先让Popuwindow消失
                mPopupMenu.dismiss();
                //设置一个标识,以方便做对应LinerLayout的点击事件.
                switch (menuIndex) {
                    case 0:
                        //获取点击对应条目的文本数据
                        String currentProduct = mMenuData1.get(position).get("name");
                        //把文本数据设置到原始布局里的文本
                        if (currentProduct.equals("价格由高到低")){
                            requestEmit("priceDesc");
                        }if (currentProduct.equals("价格由低到高")){
                        requestEmit("priceAsc");
                    }

                        mProductTv.setText(currentProduct);
                        break;
                    case 2:
                        String currentAct = mMenuData3.get(position).get("name");
                        mActivityTv.setText(currentAct);
                        if (currentAct.equals("红包由高到低")){
                            requestEmit("couponMoneyDesc");
                        }if (currentAct.equals("红包由低到高")){
                        requestEmit("couponMoneyAsc");
                    }
                        requestEmit(currentAct);
                        break;
                    default:
                        break;
                }
            }
        });
    }


    private void initView() {
        searchBeanlist = new ArrayList<>();
        supplier_list_xaiohui = (ImageView) findViewById(R.id.supplier_list_xaiohui);
        supplier_list_xaiohui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mActivity = (LinearLayout) findViewById(R.id.supplier_list_activity3);
        mActivityTv = (TextView) findViewById(R.id.supplier_list_activity_tv3);
        mProductTv = (TextView) findViewById(R.id.supplier_list_product_tv3);
        mProduct = (LinearLayout) findViewById(R.id.supplier_list_product3);
        tv_searsss = (TextView) findViewById(R.id.tv_searsss);
        mSortTv = (TextView) findViewById(R.id.supplier_list_sort_tv3);
        mSortTv.setTextColor(Color.parseColor("#5a5959"));
        mSort = (LinearLayout) findViewById(R.id.supplier_list_sort3);
        mSupplierListLv = (ListView) findViewById(R.id.supplier_list_lv3);
        zhanweill = (LinearLayout) findViewById(R.id.zhanwei);
        activity_search_show_list = (XRecyclerView) findViewById(R.id.activity_search_show_list3);
        seearch_showAdapter = new Seearch_showAdapter(searchBeanlist,this);
        activity_search_show_list.setLayoutManager(new GridLayoutManager(Search_showActivity.this, 2, GridLayoutManager.VERTICAL, false));
        activity_search_show_list.setAdapter(seearch_showAdapter);
        seearch_showAdapter.setmMyItemclickListener(new Seearch_showAdapter.MyItemclickListener() {
            @Override
            public void itemclick(View view, int position) {
                spuPlatform = searchBeanlist.get(position).getSpuPlatform();
                if (searchBeanlist.get(position).getSpuPlatform().equals("yh")) {
                    Intent intent = new Intent(Search_showActivity.this, Red_PacketActivity.class);
                    intent.putExtra("shopid", searchBeanlist.get(position).getId());
                    intent.putExtra("typex", searchBeanlist.get(position).getSpuPlatform());
                    startActivity(intent);
                } else {
                    location = position;
                    if (searchBeanlist.get(position).getSpuPlatform().equals("yh")) {
                        Intent intent = new Intent(Search_showActivity.this, Red_PacketActivity.class);
                        intent.putExtra("shopid", searchBeanlist.get(position).getId());
                        intent.putExtra("typex",searchBeanlist.get(position).getSpuPlatform());
                        startActivity(intent);
                    } else {
                        if (searchBeanlist.get(position).getSpuPlatform().equals("jd")) {
                            if (searchBeanlist.get(position).getCouponMoney().equals("")) {
                                initJDputong();
                                if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                                    try {
                                        KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                    } catch (KeplerBufferOverflowException e) {
                                        e.printStackTrace();
                                    }

                                }else {
                                    final LoginListener mLoginListener = new LoginListener() {
                                        @Override
                                        public void authSuccess(Object token) {
                                            // TODO Auto-generated method stub
                                            Toast.makeText(Search_showActivity.this, token + "", Toast.LENGTH_SHORT).show();
                                            //                showToken();

                                            if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
                                                try {
                                                    KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                } catch (KeplerBufferOverflowException e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                        }

                                        @Override
                                        public void authFailed(int errorCode) {
                                            // TODO Auto-generated method stub
                                            switch (errorCode) {
                                                case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
                                                default:
                                                    break;
                                            }
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
                                            Log.e("jdSHOUQUAN", errorCode + ":authFailed");
                                        }
                                    };
                                    KeplerApiManager.getWebViewService().login(Search_showActivity.this, mLoginListener);
                                }
//                                Intent intent = new Intent(Search_showActivity.this, HtmlActivity.class);
//                                intent.putExtra("data", datalisnajie);
//                                intent.putExtra("shopid", searchBeanlist.get(location).getId());
//                                startActivity(intent);
                            }
                            if (searchBeanlist.get(position).getCouponMoney() != "") {
                                if (searchBeanlist.get(position).getCouponMoney().equals("0.0")) {
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
                                    map.put("spuId", searchBeanlist.get(location).getId());
                                    map.put("appid", AUniqueIdentifier.getDeviceId(Search_showActivity.this));
                                    OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+ searchBeanlist.get(location).getSpuPlatform()+"/getConUrl").build().execute(new StringCallback() {
                                        @Override
                                        public void onError(Request request, Exception e) {

                                        }

                                        @Override
                                        public void onResponse(String response) {
                                            Log.e("优惠二和一数据", response);
                                            Gson gson = new Gson();
                                            jDlianjiebean = gson.fromJson(response, JDlianjie.class);
                                            datayouhui = jDlianjiebean.getData();
                                            if (jDlianjiebean.getCode().equals("10000")) {
                                                Intent intent = new Intent(Search_showActivity.this, JDred_packetActivity.class);
                                                intent.putExtra("shopid", searchBeanlist.get(location).getId());
                                                startActivity(intent);
                                            }
                                        }
                                    });

                                } else {
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
                                    map.put("spuId", searchBeanlist.get(location).getId());
                                    map.put("appid", AUniqueIdentifier.getDeviceId(Search_showActivity.this));

                                    OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+searchBeanlist.get(location).getSpuPlatform()+"/getConUrl").build().execute(new StringCallback() {
                                        @Override
                                        public void onError(Request request, Exception e) {

                                        }

                                        @Override
                                        public void onResponse(String response) {
                                            Log.e("优惠二和一数据", response);
                                            Gson gson = new Gson();
                                            jDlianjiebean = gson.fromJson(response, JDlianjie.class);
                                            datayouhui = jDlianjiebean.getData();
                                            if (jDlianjiebean.getCode().equals("10000")) {
                                                if (jDlianjiebean.getData() != null) {
                                                    if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                                                        try {
                                                            KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                        } catch (KeplerBufferOverflowException e) {
                                                            e.printStackTrace();
                                                        }

                                                    }else {
                                                        final LoginListener mLoginListener = new LoginListener() {
                                                            @Override
                                                            public void authSuccess(Object token) {
                                                                // TODO Auto-generated method stub
                                                                Toast.makeText(Search_showActivity.this, token + "", Toast.LENGTH_SHORT).show();
                                                                //                showToken();

                                                                if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
                                                                    try {
                                                                        KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                                    } catch (KeplerBufferOverflowException e) {
                                                                        e.printStackTrace();
                                                                    }
                                                                }

                                                            }

                                                            @Override
                                                            public void authFailed(int errorCode) {
                                                                // TODO Auto-generated method stub
                                                                switch (errorCode) {
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
                                                                    default:
                                                                        break;
                                                                }
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
                                                                Log.e("jdSHOUQUAN", errorCode + ":authFailed");
                                                            }
                                                        };
                                                        KeplerApiManager.getWebViewService().login(Search_showActivity.this, mLoginListener);
                                                    }
//                                                    Intent intent = new Intent(Search_showActivity.this, HtmlActivity.class);
//                                                    intent.putExtra("shopid", searchBeanlist.get(location).getId());
//                                                    intent.putExtra("data", datayouhui);
//                                                    startActivity(intent);

                                                }
                                            }
                                        }
                                    });


                                }
                            }


                        }
                    }
                }
            }
        });

        activity_search_show_list.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                curr = 0;
                requestEmit("");
            }

            @Override
            public void onLoadMore() {
                curr++;
                requestEmit("");
            }
        });
        requestEmit("");
        if (SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")){
            dialog_search_share.setVisibility(View.VISIBLE);
        }else{
            dialog_search_share.setVisibility(View.GONE);
        }
        dialog_search_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("数据Toady", Contig.checkedIndexltmalgrid + "-=====Contig.checkedIndex===id");
                if (Contig.checkedIndexltmalgrid.size() == 0) {
                    Toast.makeText(Search_showActivity.this, "没有选择，请选择再分享！", Toast.LENGTH_SHORT).show();
                } else {
                    for (int i = 0; i < Contig.checkedIndexltmalgrid.size(); i++)
                        idlist.add(searchBeanlist.get(Contig.checkedIndexltmalgrid.get(i)).getId());

                    Log.e("数据Toady", idlist + "-===========id");


                    StringBuffer permission = new StringBuffer();
                    for (int i = 0; i < idlist.size(); i++) {
                        if (i == 0) {
                            permission.append(idlist.get(i));
                        } else {
                            permission.append("," + idlist.get(i));
                        }
                        Contig.listididtml.add(idlist.get(i));

                    }
//                    LoadStoreList(0, 0, Contig.listidid);

                    ApiManager
                            .getInstance()
                            .getApiServer()
                            .getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(Search_showActivity.this), permission.toString())
                            .compose(ApiManager.<ShareImageBean>handlResult())
                            .subscribe(new ObserverCallback<ShareImageBean>(Search_showActivity.this) {
                                @Override
                                protected void onSuccessful(ShareImageBean resp) {

                                    saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXHY);
                                    if (Contig.checkedIndexltmalgrid.size() > 0) {
                                        for (int a = 0; a < Contig.checkedIndexltmalgrid.size(); a++) {
                                            Contig.ShareListtmll.add(searchBeanlist.get(Contig.checkedIndexltmalgrid.get(a)).getId());
                                        }
                                    }
                                    seearch_showAdapter = new Seearch_showAdapter(searchBeanlist,Search_showActivity.this);
                                    activity_search_show_list.setLayoutManager(new GridLayoutManager(Search_showActivity.this, 2, GridLayoutManager.VERTICAL, false));
                                    activity_search_show_list.setAdapter(seearch_showAdapter);

                                }

                                @Override
                                protected void onError(String code, String errMsg) {
                                    ToastUtils.showShortSafe(errMsg);
                                }
                            });
                    idlist.clear();
                }

            }
        });
    }
    private void saveImage(List<String> imageUrls, final String cconten, final int type) {
        try {
            Log.v("shiran", "------------saveImage------------");

            final LoadingDialog dialog = new LoadingDialog(Search_showActivity.this);
            dialog.setContent("正在生成图片请稍后");


            Observable.just(imageUrls)
                    .map(new Function<List<String>, List<String>>() {

                        @Override
                        public List<String> apply(List<String> list) throws Exception {

                            List<String> paths = new ArrayList<String>();
                            for (String s : list) {
                                FutureTarget<File> future = Glide.with(APP.getInstance())
                                        .load(s)
                                        .downloadOnly(500, 500);
                                File cacheFile = future.get();
                                String uuid = UUID.randomUUID().toString();
                                FileIOUtils.writeFileFromIS(savePath + uuid + ".jpg", new FileInputStream(cacheFile));
                                String pat = savePath + uuid + ".jpg";
                                paths.add(pat);

                            }


                            return paths;
                        }
                    }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<String>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            if (dialog != null && !dialog.isShowing()) {
                                dialog.show();
                            }
                        }

                        @Override
                        public void onNext(List<String> value) {
                            LogUtils.e(value);
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                                dialog.cancel();
                            }

                            switch (type) {
                                case SHARET_WXHY:


                                    ShareUtils.sharePicToFriendNoSDK(Search_showActivity.this, value);
//                                        ClipboardUtils.copyText(cconten);
//                                        ToastUtils.showShortSafe("内容已复制!");
                                    break;
//                            case SHARET_WXPYQ:
//                                ShareUtils.share9PicsToWXCircle(getActivity(), "", value);
//                                break;
                                default:
                                    break;
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                                dialog.cancel();
                            }
                        }

                        @Override
                        public void onComplete() {
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                                dialog.cancel();
                            }
                        }
                    });
        }catch (Exception e){}
    }
    private void initJDputong(){
        Map<String,String>map=new HashMap<String, String>();
        map.put("spuId",searchBeanlist.get(location).getId());
        map.put("appid", AUniqueIdentifier.getDeviceId(Search_showActivity.this));
        map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));

        OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+searchBeanlist.get(location).getSpuPlatform()+"/getUrl").build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Log.e("fgdgfe",response);
                Gson gson=new Gson();
                JDlianjie jDlianjie = gson.fromJson(response, JDlianjie.class);
                datalisnajie = jDlianjie.getData();
                Log.e("kfjsdkghdfk", datalisnajie);

            }
        });

    }
    @OnClick({ R.id.supplier_list_product3,R.id.supplier_list_sort3,R.id.supplier_list_activity3 ,R.id.supplier_list_sort_tv3})
    public void onClick(View view){
        switch (view.getId()) {
            //第一个Popuwindow所执行的点击后的逻辑
            case R.id.supplier_list_product3:
                mSortTv.setTextColor(Color.parseColor("#5a5959"));
                //设置其TextView点击时为绿色
                mProductTv.setTextColor(Color.parseColor("#ff2040"));
                //设置Popuwindow里的ListView适配器
                mPopListView.setAdapter(mMenuAdapter1);
                //让Popuwindow显示出来.  参数1:VIew对象,决定了在哪个控件下显示,  参数2决定了Popuwindow的坐标,X轴,Y轴
//                mPopupMenu.showAsDropDown(mProduct);
                mPopupMenu.showAsDropDown(mProduct, 0, 0, Gravity.BOTTOM);
                menuIndex=0;
                break;
            //第2个Popuwindow所执行的点击后的逻辑
            case R.id.supplier_list_sort3:
//                mSortTv.setTextColor(Color.parseColor("#39ac69"));
//                mPopListView.setAdapter(mMenuAdapter2);
//                mPopupMenu.showAsDropDown(mSort);
//                mSortTv.setTextColor(Color.parseColor("#ff2040"));
                menuIndex=1;
                break;
            case R.id.supplier_list_sort_tv3:
//                    flag=true;
                mSortTv.setTextColor(Color.parseColor("#ff2040"));
                menuIndex = 1;
                break;
            //第3个Popuwindow所执行的点击后的逻辑
            case R.id.supplier_list_activity3:
                mSortTv.setTextColor(Color.parseColor("#5a5959"));
                mActivityTv.setTextColor(Color.parseColor("#ff2040"));
                mPopListView.setAdapter(mMenuAdapter3);
//                mPopupMenu.showAsDropDown(mActivity);
                mPopupMenu.showAsDropDown(mProduct, 0, 0, Gravity.BOTTOM);
                menuIndex=2;
                break;

            default:
                break;
        }
    }
}
